package com.sdp.right.control;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.sdp.core.bizc.annotation.ViewColumn;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.db.sys_entity_field.service.ISysEntityFieldService;
import com.sdp.right.db.sys_entity_info.service.ISysEntityInfoService;
import com.sdp.right.entity.SysEntityField;
import com.sdp.right.entity.SysEntityInfo;
import com.sdp.right.utils.RightConstants;



/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2023-11-13
 */
@RestController
@RequestMapping("/SysEntityInfoController")
public class SysEntityInfoController {
	
	@Autowired
	private ISysEntityInfoService iSysEntityInfoService;
	
	@Autowired
	private ISysEntityFieldService iSysEntityFieldService;
	
	@Autowired
	private Query query;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysEntityInfoService, SysEntityInfo.class, dataCenter));
	}

	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody SysEntityInfo entityInfo) {
		if(entityInfo==null) {
			return Result.error("实体信息为空");
		}
		if(StringUtils.isEmpty(entityInfo.getTableName())) {
			return Result.error("数据库表名为空");
		}
		if(StringUtils.isEmpty(entityInfo.getEntityDesc())) {
			return Result.error("备注信息为空");
		}
		if(StringUtils.isEmpty(entityInfo.getEntityClassName())) {
			return Result.error("实体名称为空");
		}
		if(StringUtils.isEmpty(entityInfo.getKeyId())) {
			iSysEntityInfoService.save(entityInfo);
		}else {
			iSysEntityInfoService.updateById(entityInfo);
		}
	
		return Result.ok();
	}
	
	@PostMapping(value = "/initEntity")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> initEntityInfo(@RequestBody SysEntityInfo entityInfo) {
		if(StringUtils.isEmpty(entityInfo)) {
			return Result.error("初始化的实体信息不存在");
		}
		
		if(StringUtils.isEmpty(entityInfo.getEntityClassName())) {
			return Result.error("初始化的实体名不存在");
		}
		
		Map<String,SysEntityField> oldFieldMap =  new HashMap<>();
		
		if(!StringUtils.isEmpty(entityInfo.getKeyId())) {
			List<SysEntityField> fields = iSysEntityFieldService.querySysEntityFieldByClassName(entityInfo.getEntityClassName());
			for(SysEntityField f : fields) {
				oldFieldMap.put(f.getEntityField(), f);
			}
		}
		
		iSysEntityInfoService.removeSysEntityInfoByClassName(entityInfo.getEntityClassName());
		iSysEntityFieldService.removeSysEntityFieldByClassName(entityInfo.getEntityClassName());
		
		List<SysEntityField> fieldList = new ArrayList<>();
		entityInfo.setSystemNo(ContextManager.getContextData(CoreConstantsEnum.header中的模块参数名.getCode()));
		
		
		try {
			Class<?> clazz = Class.forName(entityInfo.getEntityClassName());

			TableName tableName = clazz.getAnnotation(TableName.class);
			if(!StringUtils.isEmpty(tableName) && !StringUtils.isEmpty(tableName.value())) {
				entityInfo.setTableName(tableName.value());
			}else {
				entityInfo.setTableName(clazz.getSimpleName());
			}
			entityInfo.setEntityDesc(clazz.getSimpleName());
			
			Field[] fields = clazz.getDeclaredFields();
			TableField tableField; //字段注解
			ViewColumn viewColumn;//视图字段注解
			TableId tableId; //主键注解
			boolean isView = false;
			for (int i=0;i<fields.length;i++){
				Field field = fields[i];
				if(Modifier.toString(field.getModifiers()).indexOf("static")<0) {
					tableField = field.getAnnotation(TableField.class);
					viewColumn = field.getAnnotation(ViewColumn.class);
					tableId = field.getAnnotation(TableId.class);
					
					if(isView) {
						viewEntity(field, viewColumn, entityInfo, fieldList,oldFieldMap);
						continue;
					}
					
					if(viewColumn!=null) {
						isView = true;
						viewEntity(field, viewColumn, entityInfo, fieldList,oldFieldMap);
					}
					
					
					if(!isView) {
						if(tableField==null && tableId==null) {
							return Result.error(entityInfo.getEntityClassName()+" 实体中，有字段未配置TableField 或者 TableId注解");
						}
						entity(field, tableField, tableId, entityInfo, fieldList,oldFieldMap);
					}
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.error("初始化失败");
		}
		iSysEntityInfoService.save(entityInfo);
		iSysEntityFieldService.saveBatch(fieldList);
		return Result.ok(entityInfo);
	}
	
	
	private void entity(Field field,TableField tableField,TableId tableId,SysEntityInfo entityInfo,List<SysEntityField> fieldList,Map<String,SysEntityField> oldFieldMap) {
		SysEntityField f = new SysEntityField();
		entityInfo.setEntityType(RightConstants.实体类型_表.getCode());
		
		f.setEntityField(field.getName());
		f.setEntityClassName(entityInfo.getEntityClassName());
		f.setEntityFieldTitle(field.getName());
		f.setDbField(tableField==null?tableId.value():tableField.value());
		
		if(oldFieldMap.size()>0 && oldFieldMap.containsKey(field.getName())) {
			f.setEntityFieldTitle(oldFieldMap.get(field.getName()).getEntityFieldTitle());
		}
		if(StringUtils.isEmpty(f.getDbField())) {
			f.setDbField(f.getEntityField());
		}
		
		fieldList.add(f);
	}
	
	private void viewEntity(Field field,ViewColumn viewColumn,SysEntityInfo entityInfo,List<SysEntityField> fieldList,Map<String,SysEntityField> oldFieldMap) {
		SysEntityField f = new SysEntityField();
		entityInfo.setEntityType(RightConstants.实体类型_视图.getCode());
		
		f.setEntityField(field.getName());
		f.setEntityClassName(entityInfo.getEntityClassName());
		f.setEntityFieldTitle(StringUtils.isEmpty(viewColumn.label())?field.getName():viewColumn.label());
		f.setDbField(viewColumn.value());
		
		if(oldFieldMap.size()>0 && oldFieldMap.containsKey(field.getName())) {
			f.setEntityFieldTitle(oldFieldMap.get(field.getName()).getEntityFieldTitle());
		}
		if(StringUtils.isEmpty(f.getDbField())) {
			f.setDbField(f.getEntityField());
		}
		fieldList.add(f);
	}
	
}

